require('normalize.css/normalize.css');
require('styles/App.scss');

import React from 'react';
import ReactDOM from 'react-dom';

// let yeomanImage = require('../images/yeoman.png');
let imageDatas = require('json!../../data/imageDatas.json');


//利用自执行函数，将图片信息转成图片URL路径信息
imageDatas = function genImageURL(imageDatasArr) {
    for(var i = 0; i < imageDatasArr.length; i++) {
        var singleImageData = imageDatasArr[i];
        singleImageData.imgURL = require('../../images/' +
         singleImageData.fileName);
        imageDatasArr[i] = singleImageData;
    }
    return imageDatasArr;
}(imageDatas);

let ImgFigure = React.createClass({
   render() {
       var styleObj = {};

       //如果props属性中指定了这张图片的位置，则使用
       if(this.props.arrange.pos) {
           styleObj = this.props.arrange.pos;
       }
     return (
             <figure className="img-figure" style={styleObj}>
                 <img src={this.props.data.imgURL} width="240px" height="240px" alt={this.props.data.title}/>
                 <figcaption>
                     <h2 className="img-title">{this.props.data.title}</h2>
                 </figcaption>
             </figure>
         );
   }
});

/**
 * 获取区间值
 * @param low
 * @param high
 * @returns {number}
 */
function getRangeRandom(low, high) {
   return Math.ceil(Math.random() * (high - low) + low);
}

class AppComponent extends React.Component  {
    constructor(props) {
        super(props);

       this.Constant = {
            //中心位置
            centerPos: {
                left: 0,
                right: 0
            },
            //水平方向取值范围
            hPosRange: {
                leftSecX: [0, 0],
                rightSecX: [0, 0],
                y: [0, 0]
            },
            //垂直方向取值范围
            vPosRange: {
                x: [0, 0],
                topY: [0, 0]
            }
        };
       this.state =  {
            imgsArrangeArr: [
                /*  {
                 pos: {
                 left: '0',
                 top: '0'
                 }
                 }*/
            ]
        };
    }

        //组件加载以后，为每张图片计算其位置的范围
     componentDidMount(){
            //首先拿到舞台的大小
            var stageDom = this.refs.stage,
            stageW  = stageDom.scrollWidth,
            stageH  = stageDom.scrollHeight,
            halfStageW = Math.ceil(stageW / 2),
            halfStageH = Math.ceil(stageH / 2),

            //拿到一个imageFigure的大小
            imgFigureDom = ReactDOM.findDOMNode(this.refs.imgFigures0),
            imgW = imgFigureDom.scrollWidth,
            imgH = imgFigureDom.scrollHeight,
            halfImgW = Math.ceil(imgW / 2),
            halfImgH = Math.ceil(imgH / 2);

            //获取中心图片位置
            this.Constant.centerPos = {
                left: halfStageW - halfImgW,
                top: halfStageH - halfImgH
            };
console.log(imgH);
console.log(imgW);
            //计算水平图片位置范围
            this.Constant.hPosRange.leftSecX[0] = 0 - halfImgW;
            this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3;
            this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW;
            this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW;
            this.Constant.hPosRange.y[0] = -halfImgH;
            this.Constant.hPosRange.y[1] = stageH - halfImgH;

            //计算垂直图片位置范围
            this.Constant.vPosRange.topY[0] = -halfImgH;
            this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3;
            this.Constant.vPosRange.x[0] = halfImgW - imgW;
            this.Constant.vPosRange.x[1] = halfImgW;

            this.rearange(0);
    }



        /**
         * 重新布局所以图片
         * @param centerIndex
         */
        rearange(centerIndex) {
            var imgsArrangeArr = this.state.imgsArrangeArr,
                Constant = this.Constant,
                centerPos = Constant.centerPos,
                hPosRange = Constant.hPosRange,
                vPosRange = Constant.vPosRange,
                hPosRangeLeftSecX = hPosRange.leftSecX,
                hPosRangerightSecX = hPosRange.rightSecX,
                hPosRangeY = hPosRange.y,
                vPosRangeTopY = vPosRange.topY,
                vPosRangeX = vPosRange.x,

                imgsArrangerTopArr = [],
                topImgNum = Math.floor(Math.random() * 2), //取一个或者不取
                topImgSpliceIndex = 0,
                imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex, 1);

                //首先居中 centerIndex的图片
                imgsArrangeCenterArr[0].pos = centerPos;


                //取出要布局上侧的图片的状态信息
                topImgSpliceIndex = Math.ceil(Math.random() * (imgsArrangeArr.length - topImgNum));
                imgsArrangerTopArr = imgsArrangeArr.splice(topImgSpliceIndex, topImgNum);

                //布局位于上侧的图片
                imgsArrangerTopArr.forEach(function (value, index) {
                    imgsArrangerTopArr[index].pos = {
                        top: getRangeRandom(vPosRangeTopY[0], vPosRangeTopY[1]),
                        left: getRangeRandom(vPosRangeX[0], vPosRangeX[1])
                    }
                });

             //   布局左右两侧图片
                var imgArrLength = imgsArrangeArr.length;
                for (var i = 0; i < imgArrLength; i++) {
                    var hPosRangeLORX = null;
                    //前半部分布局左边，有半部分布局右边
                    if(i < imgArrLength / 2) {
                        hPosRangeLORX = hPosRangeLeftSecX;
                    }else {
                        hPosRangeLORX = hPosRangerightSecX;
                    }
                    imgsArrangeArr[i].pos = {
                        top: getRangeRandom(hPosRangeY[0], hPosRangeY[1]),
                        left: getRangeRandom(hPosRangeLORX[0],hPosRangeLORX[1])
                    }
                }

                if(imgsArrangerTopArr && imgsArrangerTopArr[0]) {
                    imgsArrangeArr.splice(topImgSpliceIndex, 0 , imgsArrangerTopArr[0]);
                }
                imgsArrangeArr.splice(centerIndex, 0, imgsArrangeCenterArr[0]);
    // debugger;
                this.setState({
                   imgsArrangeArr: imgsArrangeArr
                });
        }


      render(){
          var controllerUnits = [],
              imgFigures = [];

          var _that = this;
          imageDatas.forEach((value, index) => {
              if(!_that.state.imgsArrangeArr[index]) {
                  _that.state.imgsArrangeArr[index] = {
                      pos: {
                          left: 0,
                          top: 0
                      }
                  }
              }
              imgFigures.push(<ImgFigure data={value} ref={'imgFigures'+ index } key={index}
               arrange={_that.state.imgsArrangeArr[index]} />);
          });

        return (
          // <div className="index">
          //   <img src={yeomanImage} alt="Yeoman Generator" />
          //   <div className="notice">Please edit <code>src/components/Main.js</code> to get started!</div>
          // </div>
                <section className="stage" ref="stage">
                    <section className="img-sec">
                        {imgFigures}
                    </section>
                    <nav className="controller-nav">
                        {controllerUnits}
                    </nav>
                </section>
          //       <section className="stage" ref="stage">
          //     <section className="img-sec">
          //            {ImgFigures}
          //         </section>
          //             <nav className="controller-nav">
          //                 {controllerUnits}
          //             </nav>
          //         </section>

        );
      }

};

AppComponent.defaultProps = {
};

export default AppComponent;
